class Solution {
public:
    struct Compare{
        bool operator()(pair<string,int>& p1,pair<string,int>& p2){
            if(p1.second==p2.second){
                return p1.first < p2.first;
            }
            return p1.second > p2.second;
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string,int> mp;
        for(auto& e: words){
            mp[e]++;
        }
        vector<pair<string,int>> v(mp.begin(),mp.end());
        sort(v.begin(),v.end(),Compare());
        vector<string> vv;
        for(auto& e: v){
            if(k){
                vv.push_back(e.first);
                --k;
            }else break;
        }
        return vv;
    }
};